package zzxkj.blog.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zzxkj.blog.shiro.AccountRealm;
import zzxkj.blog.shiro.AuthFilter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zzxkj
 */
@Slf4j
@Configuration
public class ShiroConfig {

    @Bean
    public SecurityManager securityManager(AccountRealm accountRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);
        log.info("------------------>securityManager注入成功");
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        // 配置登录的url和登录成功的url
        filterFactoryBean.setLoginUrl("/admin");
        filterFactoryBean.setSuccessUrl("/admin/index");
        // 配置未授权跳转页面
        filterFactoryBean.setUnauthorizedUrl("/admin");
        /**
         * 全拦截要放在后面
         * anon  游客使用
         * authc 需认证
         * ssl 必须以https
        * */
        Map<String, String> hashMap = new LinkedHashMap<>();
        hashMap.put("/admin/captcha.jpg","anon");
        hashMap.put("/admin/login","anon");
        hashMap.put("/admin", "anon");
        //使用shiro，内置过滤器，角色为admin和guest
        hashMap.put("/admin/*","roles[admin]");
        filterFactoryBean.setFilterChainDefinitionMap(hashMap);
        return filterFactoryBean;

    }

    // thymeleaf模板引擎中使用shiro标签时，要用到
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }

/*    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }*/
}
